package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public R add(Category category) {
        int count = categoryMapper.insert(category);

        if (count <= 0) {
            return R.error("添加失败");
        }
        return R.success("添加成功");
    }

    @Override
    public R findpage(Integer page, Integer pageSize) {
        Page<Category> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        Page<Category> categoryPage = categoryMapper.selectPage(p, wrapper);
        return R.success(categoryPage);
    }

    @Override
    public R removeById(Long id) {
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, id);
        List<Dish> dishes = dishMapper.selectList(dishWrapper);
        if (dishes.size() > 0) {
            return R.error("此分类下存在菜品,不能删除");
        }

        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, id);
        List<Setmeal> setmeals = setmealMapper.selectList(setmealWrapper);
        if (setmeals.size() > 0) {
            return R.error("此分类下存在套餐,不能删除");
        }
        return R.success("删除成功");
    }

    @Override
    public R modify(Category category) {
        categoryMapper.updateById(category);
        return R.success("修改成功");
    }

    @Override
    public R list(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (type != null) {
            wrapper.eq(Category::getType, type);
        }
        List<Category> categories = categoryMapper.selectList(wrapper);
        return R.success(categories);
    }
}
